package cn.qicaiwang.open.admin.controller.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.qicaiwang.open.common.constant.Constants;
import cn.qicaiwang.open.common.enums.ResultStatusCodeEnum;
import cn.qicaiwang.open.common.enums.SmsCodeEnum;
import cn.qicaiwang.open.common.response.ResponseResult;
import cn.qicaiwang.open.common.utils.AesUtil;
import cn.qicaiwang.open.common.utils.sms.TencentSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController
@RequestMapping("sms")
public class SmsController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private Executor threadPoolTaskExecutor;
    @Autowired
    private MailAccount mailTemplate;

    /**
     * 注册或登录验证码
     * @return
     */
    @GetMapping("sendMessage")
    public ResponseResult sendMessage(String mobile, String key){
        if(StrUtil.isBlank(mobile)){
            return ResponseResult.error(ResultStatusCodeEnum.MOBILE_NOT_EMPTY);
        }
        try {
            SmsCodeEnum smsCodeEnum = SmsCodeEnum.valueOf(key);
            mobile = AesUtil.decrypt(mobile);
            String captcha = RandomStringUtils.randomNumeric(6);
            redisTemplate.opsForValue().set(smsCodeEnum.getKey() + mobile, captcha, 10, TimeUnit.MINUTES);
            String finalMobile = Constants.CN_COUNTRY_CODE + mobile;
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    TencentSmsUtils.send(smsCodeEnum.getTemplateCode(), finalMobile, captcha);
                }
            });
            log.info("短信验证码:{}, type:{}, mobile:{}", captcha, smsCodeEnum, mobile);
        } catch (Exception e) {
            log.error("发送短信失败:", e);
            return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
        }
        return ResponseResult.ok();
    }

    /**
     * 注册或登录验证码
     * @return
     */
    @GetMapping("sendEmail")
    public ResponseResult sendEmail(String email, String key){
        if(StrUtil.isBlank(email)){
            return ResponseResult.error(ResultStatusCodeEnum.EMAIL_NOT_EMPTY);
        }
        try {
            SmsCodeEnum smsCodeEnum = SmsCodeEnum.valueOf(key);
            String orgEmail = AesUtil.decrypt(email);
            String captcha = RandomStringUtils.randomNumeric(6);

            redisTemplate.opsForValue().set(smsCodeEnum.getKey() + email, captcha, 10, TimeUnit.MINUTES);
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    String html = "<p>您好，您正在进行修改绑定邮箱操作，如不是本人操作请忽略。您也可以在<a href='https://banlu.qicaiwang.cn'>办鹿（小鹿线）</a>（https://banlu.qicaiwang.cn）进行查看和编辑。</p>" +
                                  "<p style='text-align: center;'>验证码为：<font size='30'>" + captcha + "</font></p>";
                    MailUtil.send(mailTemplate, orgEmail, "修改绑定邮箱操作-办鹿（小鹿线），勿回复。", html,true);
                }
            });
            log.info("短信验证码:{}, type:{}, email:{}", captcha, smsCodeEnum, orgEmail);
        } catch (Exception e) {
            log.error("发送短信失败:", e);
            return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
        }
        return ResponseResult.ok();
    }
}
